package com.hoshiicloud.goods.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hoshiicloud.common.query.OmnipotentParam;
import com.hoshiicloud.common.rpc.Response;
import com.hoshiicloud.common.update.UpdateBatchParam;
import com.hoshiicloud.common.utils.BeanUtils;
import com.hoshiicloud.goods.entity.sku.ExtSku;
import com.hoshiicloud.goods.entity.sku.ProductManage;
import com.hoshiicloud.goods.entity.spu.BaseSpu;
import com.hoshiicloud.goods.param.sku.BranchStoreProductPageParam;
import com.hoshiicloud.goods.param.sku.ProductManageAddParam;
import com.hoshiicloud.goods.param.sku.ProductManageQueryParam;
import com.hoshiicloud.goods.param.sku.ProductManageUpdateParam;
import com.hoshiicloud.goods.service.ExtSkuService;
import com.hoshiicloud.goods.service.ProductManageService;
import com.hoshiicloud.goods.vo.BranchStoreGoodsVo;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 商品sku分配 控制器
 * </p>
 * 2019-06-04 zhangshuhu
 */
@Slf4j
@Validated
@RestController
@RequestMapping("/goods/product-manage")
@Api(value = "商品sku分配", tags = {"商品sku分配"})
public class ProductManageController {

    @Autowired
    private ProductManageService productManageService;
    @Autowired
    private ExtSkuService extSkuService;

    @ApiOperation(value = "分页查询商品sku分配")
    @PostMapping("/query/page")
    public Response< Page<ProductManage>> page(@RequestBody ProductManageQueryParam param) {
        try {
            log.info("分页查询商品sku分配");
            QueryWrapper<ProductManage> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(param.getCompanyId() != null, ProductManage::getCompanyId, param.getCompanyId())
                    .eq(param.getPlatformId() != null, ProductManage::getPlatformId, param.getPlatformId())
                    .eq(param.getStoreId() != null, ProductManage::getStoreId, param.getStoreId())
                    .eq(param.getSource() != null, ProductManage::getSource, param.getSource())
                    .eq(param.getSkuId() != null, ProductManage::getSkuId, param.getSkuId())
                    .eq(StringUtils.isNotBlank(param.getSkuNo()), ProductManage::getSkuNo, param.getSkuNo())
                    .eq(StringUtils.isNotBlank(param.getSkuName()), ProductManage::getSkuName, param.getSkuName())
                    .eq(StringUtils.isNotBlank(param.getSpec()), ProductManage::getSpec, param.getSpec())
                    .eq(StringUtils.isNotBlank(param.getUnit()), ProductManage::getUnit, param.getUnit())
                    .eq(param.getQuantity() != null, ProductManage::getQuantity, param.getQuantity())
                    .eq(param.getFreezes() != null, ProductManage::getFreezes, param.getFreezes())
                    .eq(StringUtils.isNotBlank(param.getRemark()), ProductManage::getRemark, param.getRemark())
                    .eq(param.getDeleted() != null, ProductManage::getDeleted, param.getDeleted())
                    .notIn(CollectionUtils.isNotEmpty(param.getBaseSkuIdList()), ProductManage::getBaseSkuId, param.getBaseSkuIdList());
            Page<ProductManage> page = new Page<>(Long.parseLong(param.getPageNumber()), Long.parseLong(param.getPageSize()));
            String key = "ProductManageQueryParam{" + param.toString() + "},Page{pageNumber=" + param.getPageNumber() + ",pageSize=" + param
                    .getPageSize() + "}";

            return Response.data(productManageService.getPage(page, queryWrapper, key));
        } catch (Exception e) {
            log.error("分页查询商品sku分配异常", e);
            return Response.failed("分页查询商品sku分配异常");
        }
    }

    @ApiOperation(value = "查询商品分配表数据")
    @PostMapping("/query/list")
    public Response<List<ProductManage>> listByParam(@RequestBody ProductManageQueryParam param) {
        try {
            log.info("查询商品sku分配");
            QueryWrapper<ProductManage> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(param.getCompanyId() != null, ProductManage::getCompanyId, param.getCompanyId())
                    .eq(param.getPlatformId() != null, ProductManage::getPlatformId, param.getPlatformId())
                    .eq(param.getStoreId() != null, ProductManage::getStoreId, param.getStoreId())
                    .eq(param.getSource() != null, ProductManage::getSource, param.getSource())
                    .eq(param.getSkuId() != null, ProductManage::getSkuId, param.getSkuId())
                    .eq(param.getBaseSkuId() != null, ProductManage::getBaseSkuId, param.getBaseSkuId())
                    .eq(StringUtils.isNotBlank(param.getSkuNo()), ProductManage::getSkuNo, param.getSkuNo())
                    .eq(StringUtils.isNotBlank(param.getSkuName()), ProductManage::getSkuName, param.getSkuName())
                    .eq(StringUtils.isNotBlank(param.getSpec()), ProductManage::getSpec, param.getSpec())
                    .eq(StringUtils.isNotBlank(param.getUnit()), ProductManage::getUnit, param.getUnit())
                    .eq(param.getQuantity() != null, ProductManage::getQuantity, param.getQuantity())
                    .eq(param.getFreezes() != null, ProductManage::getFreezes, param.getFreezes())
                    .eq(StringUtils.isNotBlank(param.getRemark()), ProductManage::getRemark, param.getRemark())
                    .eq(param.getDeleted() != null, ProductManage::getDeleted, param.getDeleted())
                    .notIn(CollectionUtils.isNotEmpty(param.getBaseSkuIdList()), ProductManage::getBaseSkuId, param.getBaseSkuIdList());
            return Response.data(productManageService.list(queryWrapper));
        } catch (Exception e) {
            log.error("查询商品sku分配异常", e);
            return Response.failed("查询商品sku分配异常");
        }
    }


    @GetMapping("/{id}")
    @ApiOperation(value = "根据id查询商品sku分配")
    @ApiParam(name = "id", value = "主键ID", required = true)
    public Response queryById(@PathVariable("id") Long id) {
        return Response.data(productManageService.getById(id));
    }

    @GetMapping("/getOneByStoreIdAndSkuId")
    @ApiOperation(value = "根据店铺ID，skuid查询商品sku分配")
    @ApiParam(name = "id", value = "主键ID", required = true)
    public Response getOneByStoreIdAndSkuId(@RequestParam Map<String, Object> map) {
        QueryWrapper<ProductManage> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(ProductManage::getStoreId, Long.valueOf(map.get("storeId").toString()))
                .eq(ProductManage::getSkuId, Long.valueOf(map.get("extSkuId").toString()));
        return Response.data(productManageService.getOne(queryWrapper));
    }

    /**
     * @param param
     * @return com.hoshiicloud.common.rpc.Response
     * @description: 新增
     */
    @PostMapping("/save")
    @ApiOperation(value = "新增商品sku分配")
    public Response save(@RequestBody @Valid ProductManageAddParam param) {
        // Bean数据转换
        ProductManage entity;
        try {
            entity = BeanUtils.covertType(param, ProductManage.class);
        } catch (Exception e) {
            log.error("Bean转换异常", e);
            return Response.failed("Bean转换异常");
        }
        return Response.data(productManageService.save(entity));
    }

    /**
     * @param param
     * @return com.hoshiicloud.common.rpc.Response
     * @description: 修改商品sku分配
     */
    @PutMapping("/update")
    @ApiOperation(value = "修改商品sku分配")
    public Response update(@RequestBody @Valid ProductManageUpdateParam param) {
        // Bean数据转换
        ProductManage entity;
        try {
            entity = BeanUtils.covertType(param, ProductManage.class);
        } catch (Exception e) {
            log.error("Bean转换异常", e);
            return Response.failed("Bean转换异常");
        }
        return Response.data(productManageService.updateById(entity));
    }

    /**
     * @param id
     * @return com.hoshiicloud.common.rpc.Response
     * @description: 删除商品sku分配
     */
    @DeleteMapping("/delete/{id}")
    @ApiOperation(value = "删除商品sku分配")
    @ApiParam(name = "id", value = "主键ID", required = true)
    public Response delete(@PathVariable("id") Long id) {
        return Response.data(productManageService.deleteById(id));
    }

    /**
     * @Author:campchen
     * @Description: StringUtils.join(ids, " ") 为缓存中添加唯一KEY  如不合适可选择更好方法
     * @Date:上午 10:18 2019/5/11
     * @Param: ids
     * @return: com.hoshiicloud.common.rpc.Response
     */
    @ApiOperation(value = "根据id集合查询商品sku分配")
    @GetMapping("/getByIds")
    public Response getByIds(@RequestParam List<Long> ids) {

        if (CollectionUtils.isEmpty(ids)) {
            return Response.failed("id不能为空");
        }
        ids.sort(null);
        return Response.data(productManageService.getByIds(ids, StringUtils.join(ids, "")));
    }

    @ApiOperation(value = "查询分店商品信息")
    @PostMapping("/listBranchStoreGoods")
    public Response<Page<BranchStoreGoodsVo>> listBranchStoreGoods(@RequestBody BranchStoreProductPageParam param) {
        return Response.data(productManageService.listBranchStoreGoodsByStoreId(param));
    }




    @ApiOperation(value = "批量保存")
    @PostMapping("/saveBatch")
    public Response<Boolean> saveBatch(@RequestBody List<ProductManage> list) {
        if (CollectionUtils.isEmpty(list)) {
            return Response.data(true);
        }
        return Response.data(productManageService.saveBatch1(list));
    }

    @ApiOperation(value ="批量更新")
    @PostMapping("/updateBatch")
    public Response updateBatch(@RequestBody OmnipotentParam<ProductManage> param) {
        return Response.data(productManageService.updateBatch(param));
    }


    private QueryWrapper<ProductManage> getProductManageQueryWrapper(@RequestBody @Valid ProductManageQueryParam param) {
        QueryWrapper<ProductManage> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq((param.getCompanyId() != null), ProductManage::getCompanyId, param.getCompanyId())
                .eq((param.getPlatformId() != null), ProductManage::getPlatformId, param.getPlatformId())
                .eq((param.getStoreId() != null), ProductManage::getStoreId, param.getStoreId())
                .eq((param.getSource() != null), ProductManage::getSource, param.getSource())
                .eq((param.getSkuId() != null), ProductManage::getSkuId, param.getSkuId())
                .eq(StringUtils.isNotBlank(param.getSkuNo()), ProductManage::getSkuNo, param.getSkuNo())
                .eq(StringUtils.isNotBlank(param.getSkuName()), ProductManage::getSkuName, param.getSkuName())
                .eq(StringUtils.isNotBlank(param.getSpec()), ProductManage::getSpec, param.getSpec())
                .eq(StringUtils.isNotBlank(param.getUnit()), ProductManage::getUnit, param.getUnit())
                .eq((param.getQuantity() != null), ProductManage::getQuantity, param.getQuantity())
                .eq((param.getFreezes() != null), ProductManage::getFreezes, param.getFreezes())
                .eq(StringUtils.isNotBlank(param.getRemark()), ProductManage::getRemark, param.getRemark())
                .eq((param.getDeleted() != null), ProductManage::getDeleted, param.getDeleted());
        return queryWrapper;
    }
}
